//
//  WaitingRepairViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/7/17.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "WaitingRepairViewController.h"
#import "WaitingRepairTableViewCell.h"
#import "WaitingRepairChooseViewController.h"
#import "BGSlideView.h"
#import "RepairByChooseDateViewController.h"
#import "WaitingRepairTableViewCell2.h"
#import "WaitingRepairTableViewCell3.h"
#import "WaitingRepairTableViewCell4.h"


#define kCellName @"WaitingRepairTableViewCell"
#define kCellName2 @"WaitingRepairTableViewCell2"
#define kCellName3 @"WaitingRepairTableViewCell3"
#define kCellName4 @"WaitingRepairTableViewCell4"



#define kPageSize @"20"

/*
 待维护店铺如何计算的：
 1、【每晚9点】统计每台已铺充电宝在线时长，【每晚10点】更新数据；
 2、统计每个已铺店铺所拥有的充电宝是否都【满足】在线【180分钟】
 只要有1台不满足 该店铺就将被添加到【待维护店铺】中（标记为第二日要维护的）
 3、今日数据更新后，请点击【维护成功】，确认【待维护店铺】是否已维护成功
 4、维护成功标准：【今日】待维护店铺所拥有的充电宝，在【今日】全部都满足了【在线180分钟】，标记维护成功，否则依然是【待维护店铺】
 */

@interface WaitingRepairViewController ()<UITableViewDelegate,UITableViewDataSource,WaitingRepairChooseViewControllerDelegate,RepairByChooseDateViewControllerDelegate>
{
    NSString *_chooseType;
    NSInteger _pageIndex;
    NSString *_chooseDate;
//    NSString *_chooseType;
}
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) BGSlideView *slideView;
@end

@implementation WaitingRepairViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UISetting];
    [self loadData];
}

- (void)UISetting{
//    _chooseDate = [BGDateHelper seeDayAroundToday:0][0];
//    _chooseType = @"0";
    _dataArray = [NSMutableArray array];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageIndex = 0;
        [self loadData];
        [_tableView.mj_header endRefreshing];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        _pageIndex ++;
        [self loadData];
        [_tableView.mj_footer endRefreshing];
    }];
    
    _topView.alpha = 0.8;
    _topView.layer.masksToBounds = YES;
    _topView.layer.cornerRadius = 5.f;
    
    _topView.layer.borderColor = [kColorFrom0x(0xf5f5f5) CGColor];
    _topView.layer.borderWidth = 1.f;
    
    _viewYiPushe.backgroundColor = kColorFrom0x(0xb8b8b8);
    
//    [self checkDate:[BGDateHelper seeDay][5]];
}

- (void)checkDate:(NSString *)nowDate{
    NSString *targetDate  =[NSString stringWithFormat:@"%@ 22:00:00",[BGDateHelper seeDay][0]];
    
    NSString *targetDateNum = [BGDateHelper getTimeStempByString:targetDate havehh:YES];
    
//    NSString *nowDate = [NSString stringWithFormat:@"%@",[BGDateHelper seeDay][5]];
    
    NSString *nowDateNum = [BGDateHelper getTimeStempByString:nowDate havehh:YES];
    
    NSString *zhengdian = [NSString stringWithFormat:@"%@ 00:00:00",[BGDateHelper seeDayAroundToday:1][0]];
    NSString *zhengdianNum = [BGDateHelper getTimeStempByString:zhengdian havehh:YES];
    
    NSLog(@"targetDate -> %@ ; targetDateNum -> %@",targetDate ,targetDateNum);
    
    NSLog(@"nowDate -> %@ ; nowDateNum -> %@",nowDate,nowDateNum);
    
    NSLog(@"zhengdian -> %@ ; zhengdianNum -> %@",zhengdian,zhengdianNum);
    
    if (nowDateNum.longLongValue - zhengdianNum.longLongValue < 7200 || targetDateNum.longLongValue - nowDateNum.longLongValue > 86400) {
        _topView.hidden = NO;
    }else{
        _topView.hidden = YES;
    }
}

- (void)creatSideViewByContent:(NSString *)content{
    if (!_slideView) {
        _slideView = [[BGSlideView alloc] initWithOrginY:69 content:content];
        [self.view addSubview:_slideView];
    }else{
        [_slideView removeFromSuperview];
        _slideView = nil;
        _slideView = [[BGSlideView alloc] initWithOrginY:69 content:content];
        [self.view addSubview:_slideView];
    }
}

#pragma mark - 网络请求
- (void)loadData{
    
    [self.hub hideAnimated:YES];
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    
    NSString *pageIndexString = [NSString stringWithFormat:@"%ld",_pageIndex];
    [[AFClient shareInstance] waitingRepairByEid:kUserId page_size:kPageSize page_index:pageIndexString date:_chooseDate status:_chooseType progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            if (_pageIndex == 0) {
                [_dataArray removeAllObjects];
            }
            _labelCount.text = [NSString stringWithFormat:@"当前筛选条件下的门店总数：%@",responseBody[@"total"]];

            for (NSDictionary *dic in responseBody[@"data"]) {
                WaitingRepairModel *model = [[WaitingRepairModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                model.store_info = dic[@"store_info"];
                
//                NSLog(@"creatTime -> %@",model.created);
                [_dataArray addObject:model];
            }
            if (_dataArray.count > 0) {
                WaitingRepairModel *model = _dataArray.firstObject;
                [self creatSideViewByContent:[NSString stringWithFormat:@"当前日期:%@",model.date]];
                
            }else{
                [self creatSideViewByContent:[NSString stringWithFormat:@"当前日期:%@",_chooseDate]];
            }
            
            
            [self creatImageBackView:_dataArray];
            [_tableView reloadData];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

#pragma mark - 点击事件
- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 tag = 200 -> yipushe
 tag = 201 -> daipushe
 */
- (IBAction)PuSheButtonClick:(UIButton *)sender {
    if (sender.tag == 200) {//已铺设
        _viewYiPushe.backgroundColor = kGreenColor;
        
        _viewDaiPushe.backgroundColor = kColorFrom0x(0xb8b8b8);
        
        _chooseType = @"0";
    }else{//待铺设
        _viewYiPushe.backgroundColor = kColorFrom0x(0xb8b8b8);
        
        _viewDaiPushe.backgroundColor = kGreenColor;
        _chooseType = @"1";
        _chooseDate = [BGDateHelper seeDay][0];

    }

    _pageIndex = 0;

    [self loadData];
}

//排序按钮
- (IBAction)chooseButtonClick:(UIButton *)sender {
    UIStoryboard *storyboard = kMainStroyboard;
//    WaitingRepairChooseViewController *chooseVC = [storyboard instantiateViewControllerWithIdentifier:@"WaitingRepairChooseViewController"];
//    chooseVC.typeValue = _chooseType;
//    chooseVC.delegate = self;
//    chooseVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
//    [self presentViewController:chooseVC animated:YES completion:nil];
    
    RepairByChooseDateViewController *repairByChooseVC = [storyboard instantiateViewControllerWithIdentifier:@"RepairByChooseDateViewController"];
    repairByChooseVC.beginDate = @"2017-07-01";
    if (_chooseDate) {
        repairByChooseVC.start = _chooseDate;
        repairByChooseVC.end = _chooseDate;
    }else{
        repairByChooseVC.start = [BGDateHelper seeDayAroundToday:0][0];
        repairByChooseVC.end = [BGDateHelper seeDayAroundToday:0][0];
    }
    repairByChooseVC.delegate = self;
    [self presentViewController:repairByChooseVC animated:YES completion:nil];
}

//点击问号
- (IBAction)wenhaoButtonClick:(UIButton *)sender {
    NSString *message = @"待维护店铺如何计算的：\n1、【每晚10点】统计当日充电宝在线时长\n2、统计已铺店铺的每个充电宝在线时长都满足180分钟\n只要一台不满足，放到第二日待维护店铺中）\n3、统计今日待维护店铺的每个充电宝在线时长都满足180分钟\n（都满足，标记维护成功）";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    //paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    //行间距
    paragraphStyle.lineSpacing = 5.0;
    NSDictionary * attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0], NSParagraphStyleAttributeName : paragraphStyle};
    NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:message];
    [attributedTitle addAttributes:attributes range:NSMakeRange(0, message.length)];
    // 下面这句话用了KVC ，将attributes的值给了alert
    [alert setValue:attributedTitle forKey:@"attributedMessage"];//attributedTitle\attributedMessage
    //end ---
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - RepairByChooseDateViewControllerDelegate

- (void)getChooseDate:(NSString *)dateString{
    _chooseDate = dateString;
    _pageIndex = 0;

    _chooseType = nil;
    _viewYiPushe.backgroundColor = kColorFrom0x(0xb8b8b8);
    _viewDaiPushe.backgroundColor = kColorFrom0x(0xb8b8b8);
    [self loadData];
}

#pragma mark - WaitingRepairChooseViewControllerDelegate

- (void)getChooseItem:(NSString *)type{
    _chooseType = type;
    NSLog(@"chooseType -> %@",type);
    _pageIndex = 0;
    [self loadData];
}

#pragma mark - tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WaitingRepairModel *model = _dataArray[indexPath.row];
    if ([model.date isEqualToString:[BGDateHelper seeDay][0]]) {
        WaitingRepairTableViewCell3 *cell = (WaitingRepairTableViewCell3 *)[tableView dequeueReusableCellWithIdentifier:kCellName3];
        [cell showDataWithModel:model];
        return cell;
    }else{
        WaitingRepairTableViewCell4 *cell = (WaitingRepairTableViewCell4 *)[tableView dequeueReusableCellWithIdentifier:kCellName4];
        [cell showDataWithModel:model];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    WaitingRepairTableViewCell *cell = (WaitingRepairTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
//    return [cell height];
    if (_dataArray.count > 0) {
        WaitingRepairModel *model = _dataArray[indexPath.row];
        if ([model.date isEqualToString:[BGDateHelper seeDay][0]]) {
            return 235;
        }else{
            return 215;
        }
    }else{
        return 215;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
